// 1. 安装路由模块
// yarn add vue-router
// 2. 导入模块
import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '../utils/localData'
// 3. 注册路由组件 <router-view> 和 <router-link>
Vue.use(VueRouter)

// 4. 路由映射关系
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import User from '../views/User.vue'
import UserEdit from '../views/UserEdit.vue'
import Article from '../views/Article.vue'
import UserFollow from '../views/UserFollow.vue'
import UserStar from '../views/UserStar.vue'
import UserComment from '../views/UserComment.vue'
import Comment from '../views/Comment.vue'
const routes = [
  { path: '/', component: Home },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/user', component: User },
  { path: '/user_edit', component: UserEdit },
  { path: '/article/:id', component: Article },
  { path: '/user_follow', component: UserFollow },
  { path: '/user_star', component: UserStar },
  { path: '/user_comment', component: UserComment },
  { path: '/comment/:id', component: Comment },
]

// 5. new 一个路由实例
const router = new VueRouter({
  // routes? 有问号的提示，说明是 VueRouter 的提示
  routes,
  mode: 'history',
})

// 路由守卫 - 就是一个路由跳转前自动执行的函数
//  to      目标路由对象地址(去哪里)
//  from    跳转前路由对象地址(从哪里来)
//  next    next是否放行(是一个函数)
router.beforeEach((to, from, next) => {
  // 在这个数据范围内的路径，都要进行登录校验
  const pathArr = ['/user', '/user_edit']
  // 部分页面访问的时候需要确认是否有token
  if (pathArr.indexOf(to.path) !== -1) {
    console.log(to.path, '需要检查的页面')
    // 如果有成功获取到token
    if (getToken()) {
      // 放行
      next()
    } else {
      // 没有 token 就跳转到登录页
      next({ path: '/login' })
    }
  }
  // 普通页面，直接放行
  else {
    next()
  }
})

// 6.1 导出路由实例
export default router
